<?php

/**
 *  获取商品价格
 */

namespace app\admin\service;

use app\admin\common\ServiceResponse;
use app\facade\Basic;
use app\admin\model\Inventory as InventoryModel;
use app\admin\model\ProductPrice as ProductPriceModel;
use app\admin\model\OrderItem as OrderItemModel;
use app\common\service\Inventory as InventoryService;
use app\common\service\CompleteNotificationService;
use app\common\service\Mail;
use think\facade\Log;

class ProductPrice extends BaseService
{

    use ServiceResponse;

    protected $model;

    public function __construct()
    {
        $this->model = new ProductPriceModel();
    }

    /**
     * @describe
     * @author: Bobo
     * @date: 2025-06-16 16:56:56 
     * @param [type] @required
     * @return Renderable
     */
    public function read($params)
    {
        $where = [];
        $query = $this->model->name('inventory')
            ->where('productid', $params['id'])
            ->where('is_futures', $params['is_futures'])
            ->where('is_del', 0)
            ->where(function ($query) {
                $query->whereRaw('(available_qty - lock_qty) > 0')
                    ->whereOr('allow_zero_stock_sale', 1);
            });

        // 仓库条件处理
        if (isset($params['warehouse_id']) && !empty($params['warehouse_id'])) {
            // 优先使用warehouse_id
            if ($params['is_futures'] == 2) {
                $where[] = ['wid', 'find in set', $params['warehouse_id']];
            } else {
                $where[] = ['wid', '=', $params['warehouse_id']];
            }
        } elseif (isset($params['fl_warehouse_id']) && !empty($params['fl_warehouse_id'])) {
            // 使用fl_warehouse_id查询子仓库
            $childWid = $this->model->name('warehouse')->where('fl_warehouse_id', $params['fl_warehouse_id'])->where('is_del', 0)->column('id');
            $allWid = array_merge($childWid, [$params['fl_warehouse_id']]);
            // 过滤空值
            $allWid = array_filter($allWid, function ($val) {
                return !empty($val) && $val !== '';
            });

            if (!empty($allWid)) {
                $where[] = function ($query) use ($allWid) {
                    foreach ($allWid as $index => $wid) {
                        if ($index === 0) {
                            $query->where('wid', 'find in set', $wid);
                        } else {
                            $query->whereOr('wid', 'find in set', $wid);
                        }
                    }
                };
            }
        }

        if (!empty($where)) {
            $query->where($where);
        }


        if (!empty($params['arrival_date'])) {
            $query->where('arrival_date', $params['arrival_date']);
        }

        $res = $query->select();
        $res = $res->toArray();

        $price_query = $this->model->name('product_price')
            ->field('
                transaction_currency_id,
                GROUP_CONCAT(DISTINCT price) as price_list,
                GROUP_CONCAT(DISTINCT first_leg_logistics_fee) as first_leg_logistics_fee_list,
                GROUP_CONCAT(DISTINCT remark) as remark_list,
                GROUP_CONCAT(id) as id_list,
                COUNT(DISTINCT price) as price_count,
                COUNT(DISTINCT remark) as remark_count,
                COUNT(DISTINCT first_leg_logistics_fee) as first_leg_logistics_fee_count
            ')
            ->where('inventory_id', 'in', array_column($res, 'id'))
            ->where('is_del', 0)
            ->group('transaction_currency_id');

        if (2 == $params['is_futures'] && !empty($params['wid'])) {
            $price_query->where('wid', 'in', $params['wid']);
        } else {
            if (!empty($params['wid'])) {
                $price_query->where('wid', $params['wid']);
            }
        }

        $priceResult = $price_query->select()->toArray();

        // 处理查询结果
        foreach ($priceResult as &$data) {
            // 如果价格种类大于1，设置为空
            if ($data['price_count'] > 1) {
                $data['price'] = '';
                // 价格不唯一时，备注也设置为空（如果备注数量大于1）
                if ($data['remark_count'] > 1) {
                    $data['remark'] = '';
                } else {
                    $data['remark'] = $data['remark_list'];
                }
                continue;
            }
            // 价格唯一时，直接使用
            $data['price'] = $data['price_list'];
            // 备注处理：只有当备注唯一时才使用，否则设置为空
            if ($data['remark_count'] > 1) {
                $data['remark'] = '';
            } else {
                $data['remark'] = $data['remark_list'];
            }
            if ($data['first_leg_logistics_fee_count'] > 1) {
                $data['first_leg_logistics_fee'] = '';
            } else {
                $data['first_leg_logistics_fee'] = $data['first_leg_logistics_fee_list'];
            }
            $data['id'] = $data['id_list'];
            $discounts = $this->model->name('product_discount')
                ->field('
                    level,
                    GROUP_CONCAT(DISTINCT num) as num,
                    GROUP_CONCAT(DISTINCT price) as price,
                    COUNT(DISTINCT price) as price_count,
                    COUNT(DISTINCT num) as num_count
                ')
                ->where('price_id', 'in', $data['id'])
                ->group('level')
                ->select()
                ->toArray();

            // 检查所有折扣的price_count和num_count是否都等于1
            $allUnique = true;
            foreach ($discounts as $discount) {
                if ($discount['price_count'] != 1 || $discount['num_count'] != 1) {
                    $allUnique = false;
                    break;
                }
            }
            if (empty($discounts)) {
                $allUnique = false;
            }
            $data['discount'] = $allUnique ? $discounts : [['level' => 1, 'num' => 100, 'price' => $data['price']]];
        }
        $priceResult = array_values($priceResult);

        $result = [
            'real_arrival_date' => array_unique(array_column($res, 'real_arrival_date')),
            'prices' => $priceResult
        ];

        return $this->success($result);
    }



    /**
     * @describe 获取商品报价列表
     * @author: Bobo
     * @date: 2025-06-12 10:50:59 
     * @param int $pageIndex 页码
     * @param int $pageSize 每页数量
     * @param array $where 查询条件
     * @param string $field 查询字段
     * @return array
     */
    public function getList($pageIndex, $pageSize, $where, $field)
    {
        // 主查询：获取库存基础数据，按产品、到货日期、期货类型分组
        $query = $this->model
            ->name('inventory')
            ->alias('i')
            ->leftJoin('product p', 'i.productid = p.id')
            ->field(
                '
                i.productid,
                i.arrival_date,
                i.is_futures,
                "全部仓库" as warehouse_name,
                NULL as fl_warehouse_id,
                NULL as warehouse_id,
                MAX(i.id) as inventory_id,
                MAX(p.cname) as cname,
                MAX(p.code) as code,
                MAX(p.hashrate) as hashrate,
                SUM(i.available_qty - i.lock_qty) as quantity,
                GROUP_CONCAT(DISTINCT i.id) as inventory_ids,
                GROUP_CONCAT(DISTINCT i.real_arrival_date) as real_arrival_date,
                MAX(i.allow_zero_stock_sale) as allow_zero_stock_sale'
            )
            ->where('i.is_del', 0)
            ->where(function ($query) {
                $query->whereRaw('(i.available_qty - i.lock_qty) > 0')
                    ->whereOr('i.allow_zero_stock_sale', 1);
            })
            ->group('i.productid, i.arrival_date, i.is_futures');

        // 应用查询条件
        if (!empty($where)) {
            $query->where($where);
        }

        $total = $query->count();
        // 应用分页
        if ($pageSize > 0) {
            $query->limit(($pageIndex - 1) * $pageSize, $pageSize);
        }

        $res = $query->select()->toArray();

        if (empty($res)) {
            return $this->success([
                'list' => [],
                'total' => 0
            ]);
        }

        // 批量获取所需数据，避免循环查询
        $this->batchLoadData($res);

        return $this->success([
            'list' => $res,
            'total' => $total
        ]);
    }

    /**
     * 批量加载数据，避免嵌套查询
     * 
     * @param array &$res 产品数据引用
     * @return void
     */
    private function batchLoadData(&$res)
    {
        // 收集所有需要查询的产品信息
        $productIds = array_column($res, 'productid');
        $arrivalDates = array_column($res, 'arrival_date');
        $futuresTypes = array_column($res, 'is_futures');

        // 批量获取所有相关库存数据
        $query = $this->model
            ->name('inventory')
            ->field('id, productid, wid, arrival_date, real_arrival_date, is_futures, available_qty, lock_qty, allow_zero_stock_sale')
            ->where('productid', 'in', $productIds)
            ->where('is_futures', 'in', $futuresTypes)
            ->where('is_del', 0)
            ->where(function ($query) {
                $query->whereRaw('(available_qty - lock_qty) > 0')
                    ->whereOr('allow_zero_stock_sale', 1);
            });

        // 处理arrival_date的查询条件，包括NULL值
        $hasNull = in_array(null, $arrivalDates, true);
        $nonNullDates = array_filter($arrivalDates, function ($date) {
            return $date !== null;
        });

        if ($hasNull && !empty($nonNullDates)) {
            // 既有NULL又有非NULL值
            $query->where(function ($q) use ($nonNullDates) {
                $q->whereNull('arrival_date')->whereOr('arrival_date', 'in', $nonNullDates);
            });
        } elseif ($hasNull) {
            // 只有NULL值
            $query->whereNull('arrival_date');
        } elseif (!empty($nonNullDates)) {
            // 只有非NULL值
            $query->where('arrival_date', 'in', $nonNullDates);
        }

        $allInventoryData = $query->select()->toArray();

        // 按产品分组库存数据
        $inventoryByProduct = [];
        foreach ($allInventoryData as $inventory) {
            $key = $inventory['productid'] . '_' . ($inventory['arrival_date'] ?? 'NULL') . '_' . $inventory['is_futures'];
            $inventoryByProduct[$key][] = $inventory;
        }

        // 批量获取所有仓库信息
        $allWarehouseIds = [];
        foreach ($allInventoryData as $inventory) {
            $widArray = explode(',', $inventory['wid']);
            foreach ($widArray as $wid) {
                $wid = trim($wid);
                if (!empty($wid)) {
                    $allWarehouseIds[] = $wid;
                }
            }
        }
        $allWarehouseIds = array_unique($allWarehouseIds);
        $warehouseData = [];
        if (!empty($allWarehouseIds)) {
            $warehouseData = $this->model
                ->name('warehouse')
                ->where('id', 'in', $allWarehouseIds)
                ->where('is_del', 0)
                ->column('*', 'id');
        }
        // 批量获取所有价格数据
        $allInventoryIds = array_column($allInventoryData, 'id');

        $priceData = [];
        $remarkData = [];
        $preWarehousePriceData = [];
        if (!empty($allInventoryIds)) {
            $priceRecords = $this->model
                ->name('product_price')
                ->where('inventory_id', 'in', $allInventoryIds)
                ->where('transaction_currency_id', 'in', [214, 4])  // 查询美金和人民币
                ->where('is_del', 0)
                ->select()
                ->toArray();
            // 按仓库ID、库存ID和货币类型组织价格和备注数据
            foreach ($priceRecords as $price) {
                $priceData[$price['wid']][$price['inventory_id']][$price['transaction_currency_id']] = $price['price'];
                $remarkData[$price['wid']][$price['inventory_id']][$price['transaction_currency_id']] = $price['remark'] ?? '';
                $preWarehousePriceData[$price['wid']][$price['inventory_id']][$price['transaction_currency_id']] = $price['first_leg_logistics_fee'] ?? '';
            }
        }

        // 处理每个产品的数据
        foreach ($res as &$value) {
            $key = $value['productid'] . '_' . ($value['arrival_date'] ?? 'NULL') . '_' . $value['is_futures'];
            $inventoryRecords = $inventoryByProduct[$key] ?? [];

            // 收集该产品的所有价格和备注（按货币分组）
            $productPricesByCurrency = [];
            $productRemarksByCurrency = [];
            $productPreWarehousePriceByCurrency = [];

            // 为现货设置 real_arrival_date 为空（现货不需要显示真实到货日期）
            if ($value['is_futures'] == 0) {
                $value['real_arrival_date'] = '';
            }

            foreach ($inventoryRecords as $inventory) {
                if ($inventory['is_futures'] == 2) {
                    // 大期货：处理多仓库
                    $widArray = explode(',', $inventory['wid']);
                    foreach ($widArray as $wid) {
                        $wid = trim($wid);
                        if (!empty($wid) && isset($priceData[$wid][$inventory['id']])) {
                            foreach ($priceData[$wid][$inventory['id']] as $currencyId => $price) {
                                $productPricesByCurrency[$currencyId][] = $price;
                            }
                        }
                        if (!empty($wid) && isset($remarkData[$wid][$inventory['id']])) {
                            foreach ($remarkData[$wid][$inventory['id']] as $currencyId => $remark) {
                                if (!empty($remark)) {
                                    $productRemarksByCurrency[$currencyId][] = $remark;
                                }
                            }
                            if (!empty($wid) && isset($preWarehousePriceData[$wid][$inventory['id']])) {
                                foreach ($preWarehousePriceData[$wid][$inventory['id']] as $currencyId => $preWarehousePrice) {
                                    $productPreWarehousePriceByCurrency[$currencyId][] = $preWarehousePrice;
                                }
                            }
                        }
                    }
                } else {
                    // 现货和在途期货：单仓库
                    $wid = trim($inventory['wid']);
                    if (!empty($wid) && isset($priceData[$wid][$inventory['id']])) {
                        foreach ($priceData[$wid][$inventory['id']] as $currencyId => $price) {
                            $productPricesByCurrency[$currencyId][] = $price;
                        }
                    }
                    if (!empty($wid) && isset($remarkData[$wid][$inventory['id']])) {
                        foreach ($remarkData[$wid][$inventory['id']] as $currencyId => $remark) {
                            if (!empty($remark)) {
                                $productRemarksByCurrency[$currencyId][] = $remark;
                            }
                        }
                    }
                    if (!empty($wid) && isset($preWarehousePriceData[$wid][$inventory['id']])) {
                        foreach ($preWarehousePriceData[$wid][$inventory['id']] as $currencyId => $preWarehousePrice) {
                            $productPreWarehousePriceByCurrency[$currencyId][] = $preWarehousePrice;
                        }
                    }
                }
            }

            // 设置价格字段
            $priceProcessed = [];
            foreach ($productPricesByCurrency as $currencyId => $prices) {
                $priceProcessed[$currencyId] = implode(',', array_unique($prices));
            }
            // 设置前置仓价格字段
            $preWarehousePriceProcessed = [];
            foreach ($productPreWarehousePriceByCurrency as $currencyId => $preWarehousePrices) {
                $preWarehousePriceProcessed[$currencyId] = implode(',', array_filter(array_unique($preWarehousePrices), function ($v) {
                    return $v !== '' && $v !== null;
                }));
            }

            // 设置备注字段
            $remarkProcessed = [];
            foreach ($productRemarksByCurrency as $currencyId => $remarks) {
                $remarkProcessed[$currencyId] = implode(',', array_unique($remarks));
            }

            $value['price'] = $priceProcessed[214] ?? '';        // 美金价格
            $value['price_rmb'] = $priceProcessed[4] ?? '';       // 人民币价格
            $value['remark'] = $remarkProcessed[214] ?? '';       // 美金备注
            $value['remark_rmb'] = $remarkProcessed[4] ?? '';     // 人民币备注
            $value['first_leg_logistics_fee'] = $preWarehousePriceProcessed[214] ?? '';        // 美金前置仓价格
            $value['first_leg_logistics_fee_rmb'] = $preWarehousePriceProcessed[4] ?? '';       // 人民币前置仓价格

            $value['transaction_currency_id'] = 214;

            if ($value['is_futures'] == 2) {
                // 大期货处理逻辑
                $this->processBigFuturesDataOptimized($value, $inventoryRecords, $warehouseData, $priceData, $remarkData, $preWarehousePriceData);
            } else {
                // 现货和在途期货处理逻辑
                $this->processRegularInventoryDataOptimized($value, $inventoryRecords, $warehouseData, $priceData, $remarkData, $preWarehousePriceData);
            }
        }
    }

    /**
     * 大期货数据处理
     * 
     * @param array &$value 产品数据引用
     * @param array $inventoryRecords 库存记录
     * @param array $warehouseData 仓库数据
     * @param array $priceData 价格数据
     * @param array $remarkData 备注数据
     * @param array $preWarehousePriceData 前置仓价格数据
     * @return void
     */
    private function processBigFuturesDataOptimized(&$value, $inventoryRecords, $warehouseData, $priceData, $remarkData, $preWarehousePriceData)
    {
        // 按父仓库分组处理多仓库记录
        $parentWarehouseGroups = [];

        foreach ($inventoryRecords as $record) {
            // 处理多仓库ID（逗号分隔）
            $widArray = explode(',', $record['wid']);

            foreach ($widArray as $singleWid) {
                $singleWid = trim($singleWid);
                if (empty($singleWid) || !isset($warehouseData[$singleWid])) continue;

                $warehouseInfo = $warehouseData[$singleWid];

                // 确定父仓库ID（如果有fl_warehouse_id则使用，否则使用自身ID）
                $parentId = $warehouseInfo['fl_warehouse_id'] ?? $singleWid;

                // 初始化父仓库分组
                if (!isset($parentWarehouseGroups[$parentId])) {
                    $parentWarehouseGroups[$parentId] = [
                        'inventory_ids' => [],
                        'quantity' => 0,
                        'allow_zero_stock_sale' => 0,
                        'real_arrival_dates' => [],
                        'warehouse_info' => null
                    ];
                }

                // 设置仓库信息（优先使用父仓库信息）
                if ($parentId == $singleWid) {
                    // 当前就是父仓库
                    $parentWarehouseGroups[$parentId]['warehouse_info'] = $warehouseInfo;
                } else {
                    // 使用父仓库信息
                    if (!$parentWarehouseGroups[$parentId]['warehouse_info'] && isset($warehouseData[$parentId])) {
                        $parentWarehouseGroups[$parentId]['warehouse_info'] = $warehouseData[$parentId];
                    }
                }

                // 累加库存数据
                $parentWarehouseGroups[$parentId]['inventory_ids'][] = $record['id'];
                $parentWarehouseGroups[$parentId]['quantity'] += ($record['available_qty'] - $record['lock_qty']);
                $parentWarehouseGroups[$parentId]['allow_zero_stock_sale'] = max(
                    $parentWarehouseGroups[$parentId]['allow_zero_stock_sale'],
                    $record['allow_zero_stock_sale']
                );

                // 收集真实到货日期
                if (!empty($record['real_arrival_date'])) {
                    $parentWarehouseGroups[$parentId]['real_arrival_dates'][] = $record['real_arrival_date'];
                }
            }
        }

        // 组装子仓库数据
        $value['children'] = [];
        foreach ($parentWarehouseGroups as $parentId => $groupData) {
            if (!$groupData['warehouse_info']) continue;

            // 获取当前仓库的价格和备注信息（按货币分组）
            $pricesByCurrency = [];
            $remarksByCurrency = [];
            $preWarehousePricesByCurrency = [];
            if (isset($priceData[$parentId])) {
                foreach ($groupData['inventory_ids'] as $inventoryId) {
                    if (isset($priceData[$parentId][$inventoryId])) {
                        foreach ($priceData[$parentId][$inventoryId] as $currencyId => $price) {
                            $pricesByCurrency[$currencyId][] = $price;
                        }
                    }
                }
            }
            if (isset($remarkData[$parentId])) {
                foreach ($groupData['inventory_ids'] as $inventoryId) {
                    if (isset($remarkData[$parentId][$inventoryId])) {
                        foreach ($remarkData[$parentId][$inventoryId] as $currencyId => $remark) {
                            if (!empty($remark)) {
                                $remarksByCurrency[$currencyId][] = $remark;
                            }
                        }
                    }
                }
            }
            if (isset($preWarehousePriceData[$parentId])) {
                foreach ($groupData['inventory_ids'] as $inventoryId) {
                    if (isset($preWarehousePriceData[$parentId][$inventoryId])) {
                        foreach ($preWarehousePriceData[$parentId][$inventoryId] as $currencyId => $preWarehousePrice) {
                            $preWarehousePricesByCurrency[$currencyId][] = $preWarehousePrice;
                        }
                    }
                }
            }
            // 处理每种货币的价格和备注去重
            $processedPrices = [];
            foreach ($pricesByCurrency as $currencyId => $prices) {
                $processedPrices[$currencyId] = implode(',', array_unique($prices));
            }

            $processedRemarks = [];
            foreach ($remarksByCurrency as $currencyId => $remarks) {
                $processedRemarks[$currencyId] = implode(',', array_unique($remarks));
            }

            $processedPreWarehousePrices = [];
            foreach ($preWarehousePricesByCurrency as $currencyId => $preWarehousePrices) {
                $processedPreWarehousePrices[$currencyId] = implode(',', array_unique($preWarehousePrices));
            }

            // 组装子仓库数据
            $value['children'][] = [
                'productid' => $value['productid'],
                'cname' => $value['cname'],
                'arrival_date' => $value['arrival_date'],
                'is_futures' => $value['is_futures'],
                'fl_warehouse_id' => $groupData['warehouse_info']['fl_warehouse_id'] ?? $parentId,
                'warehouse_id' => $parentId,
                'warehouse_name' => $groupData['warehouse_info']['name'],
                'quantity' => $groupData['quantity'],
                'inventory_ids' => implode(',', $groupData['inventory_ids']),
                'allow_zero_stock_sale' => $groupData['allow_zero_stock_sale'],
                'real_arrival_date' => implode(',', array_unique($groupData['real_arrival_dates'])),
                'price' => $processedPrices[214] ?? '',        // 美金价格
                'price_rmb' => $processedPrices[4] ?? '',      // 人民币价格
                'remark' => $processedRemarks[214] ?? '',      // 美金备注
                'remark_rmb' => $processedRemarks[4] ?? '',     // 人民币备注
                'first_leg_logistics_fee' => $processedPreWarehousePrices[214] ?? '',        // 美金前置仓价格
                'first_leg_logistics_fee_rmb' => $processedPreWarehousePrices[4] ?? ''       // 人民币前置仓价格
            ];
        }
    }

    /**
     * 普通库存数据处理
     * 
     * @param array &$value 产品数据引用
     * @param array $inventoryRecords 库存记录
     * @param array $warehouseData 仓库数据
     * @param array $priceData 价格数据
     * @param array $remarkData 备注数据
     * @param array $preWarehousePriceData 前置仓价格数据
     * @return void
     */
    private function processRegularInventoryDataOptimized(&$value, $inventoryRecords, $warehouseData, $priceData, $remarkData, $preWarehousePriceData)
    {
        // 第一步：检查是否所有库存都是一级仓库
        $allTopLevel = true;
        foreach ($inventoryRecords as $record) {
            $wid = trim($record['wid']);
            if (empty($wid) || !isset($warehouseData[$wid])) continue;

            $warehouseInfo = $warehouseData[$wid];
            // 如果有任何一个仓库不是一级仓库（有fl_warehouse_id），则需要显示三层结构
            if (!empty($warehouseInfo['fl_warehouse_id']) && $warehouseInfo['fl_warehouse_id'] != 0) {
                $allTopLevel = false;
                break;
            }
        }

        // 第二步：按父仓库分组
        $parentWarehouseGroups = [];

        foreach ($inventoryRecords as $record) {
            // 对于现货和在途期货，wid字段是单个仓库ID
            $wid = trim($record['wid']);
            if (empty($wid) || !isset($warehouseData[$wid])) continue;

            $warehouseInfo = $warehouseData[$wid];

            // 确定父仓库ID
            $parentId = $warehouseInfo['fl_warehouse_id'] ?? $wid;

            // 初始化父仓库分组
            if (!isset($parentWarehouseGroups[$parentId])) {
                $parentWarehouseGroups[$parentId] = [
                    'inventory_records' => [],
                    'total_quantity' => 0,
                    'total_allow_zero_stock_sale' => 0,
                    'total_real_arrival_dates' => [],
                    'parent_warehouse_info' => null,
                    'child_warehouses' => []
                ];
            }

            // 设置父仓库信息 - 确保获取正确的父仓库信息
            if (!$parentWarehouseGroups[$parentId]['parent_warehouse_info']) {
                // 总是尝试获取父仓库信息，即使parentId == wid
                if (isset($warehouseData[$parentId])) {
                    $parentWarehouseGroups[$parentId]['parent_warehouse_info'] = $warehouseData[$parentId];
                } else {
                    // 如果批量数据中没有，查询数据库获取父仓库信息
                    $parentWarehouseInfo = $this->model
                        ->name('warehouse')
                        ->where('id', $parentId)
                        ->where('is_del', 0)
                        ->find();
                    if ($parentWarehouseInfo) {
                        $parentWarehouseGroups[$parentId]['parent_warehouse_info'] = $parentWarehouseInfo;
                    } else {
                        // 最后的兜底方案：使用当前仓库信息
                        $parentWarehouseGroups[$parentId]['parent_warehouse_info'] = $warehouseInfo;
                    }
                }
            }

            // 添加到子仓库分组
            if (!isset($parentWarehouseGroups[$parentId]['child_warehouses'][$wid])) {
                $parentWarehouseGroups[$parentId]['child_warehouses'][$wid] = [
                    'inventory_ids' => [],
                    'quantity' => 0,
                    'allow_zero_stock_sale' => 0,
                    'real_arrival_dates' => [],
                    'warehouse_info' => $warehouseInfo
                ];
            }

            // 累加子仓库数据
            $parentWarehouseGroups[$parentId]['child_warehouses'][$wid]['inventory_ids'][] = $record['id'];
            $parentWarehouseGroups[$parentId]['child_warehouses'][$wid]['quantity'] += ($record['available_qty'] - $record['lock_qty']);
            $parentWarehouseGroups[$parentId]['child_warehouses'][$wid]['allow_zero_stock_sale'] = max(
                $parentWarehouseGroups[$parentId]['child_warehouses'][$wid]['allow_zero_stock_sale'],
                $record['allow_zero_stock_sale']
            );

            // 收集子仓库的真实到货日期
            if (!empty($record['real_arrival_date'])) {
                $parentWarehouseGroups[$parentId]['child_warehouses'][$wid]['real_arrival_dates'][] = $record['real_arrival_date'];
            }

            // 累加父仓库总数据
            $parentWarehouseGroups[$parentId]['total_quantity'] += ($record['available_qty'] - $record['lock_qty']);
            $parentWarehouseGroups[$parentId]['total_allow_zero_stock_sale'] = max(
                $parentWarehouseGroups[$parentId]['total_allow_zero_stock_sale'],
                $record['allow_zero_stock_sale']
            );

            // 收集父仓库的真实到货日期
            if (!empty($record['real_arrival_date'])) {
                $parentWarehouseGroups[$parentId]['total_real_arrival_dates'][] = $record['real_arrival_date'];
            }
        }

        // 第三步：组装数据结构（根据是否全部为顶级仓库决定层级）
        $value['children'] = [];
        foreach ($parentWarehouseGroups as $parentId => $parentGroup) {
            if (!$parentGroup['parent_warehouse_info']) continue;

            // 获取父仓库的价格和备注信息（汇总所有子仓库的价格和备注，按货币分组）
            $parentPricesByCurrency = [];
            $parentRemarksByCurrency = [];
            $parentPreWarehousePricesByCurrency = [];
            foreach ($parentGroup['child_warehouses'] as $childWarehouseId => $childData) {
                if (isset($priceData[$childWarehouseId])) {
                    foreach ($childData['inventory_ids'] as $inventoryId) {
                        if (isset($priceData[$childWarehouseId][$inventoryId])) {
                            foreach ($priceData[$childWarehouseId][$inventoryId] as $currencyId => $price) {
                                $parentPricesByCurrency[$currencyId][] = $price;
                            }
                        }
                    }
                }
                if (isset($remarkData[$childWarehouseId])) {
                    foreach ($childData['inventory_ids'] as $inventoryId) {
                        if (isset($remarkData[$childWarehouseId][$inventoryId])) {
                            foreach ($remarkData[$childWarehouseId][$inventoryId] as $currencyId => $remark) {
                                if (!empty($remark)) {
                                    $parentRemarksByCurrency[$currencyId][] = $remark;
                                }
                            }
                        }
                    }
                }

                if (isset($preWarehousePriceData[$childWarehouseId])) {
                    foreach ($childData['inventory_ids'] as $inventoryId) {
                        if (isset($preWarehousePriceData[$childWarehouseId][$inventoryId])) {
                            foreach ($preWarehousePriceData[$childWarehouseId][$inventoryId] as $currencyId => $preWarehousePrice) {
                                $parentPreWarehousePricesByCurrency[$currencyId][] = $preWarehousePrice;
                            }
                        }
                    }
                }
            }

            // 处理每种货币的价格和备注去重
            $processedParentPrices = [];
            foreach ($parentPricesByCurrency as $currencyId => $prices) {
                $processedParentPrices[$currencyId] = implode(',', array_unique($prices));
            }

            $processedParentRemarks = [];
            foreach ($parentRemarksByCurrency as $currencyId => $remarks) {
                $processedParentRemarks[$currencyId] = implode(',', array_unique($remarks));
            }

            $processedParentPreWarehousePrices = [];
            foreach ($parentPreWarehousePricesByCurrency as $currencyId => $preWarehousePrices) {
                $processedParentPreWarehousePrices[$currencyId] = implode(',', array_unique($preWarehousePrices));
            }

            // 获取所有库存ID
            $allInventoryIds = [];
            foreach ($parentGroup['child_warehouses'] as $childData) {
                $allInventoryIds = array_merge($allInventoryIds, $childData['inventory_ids']);
            }

            // 如果所有库存都是一级仓库，只显示两层结构
            if ($allTopLevel) {
                $value['children'][] = [
                    'productid' => $value['productid'],
                    'cname' => $value['cname'],
                    'arrival_date' => $value['arrival_date'],
                    'is_futures' => $value['is_futures'],
                    'fl_warehouse_id' => $parentId,
                    'warehouse_id' => null,  // 第二层的warehouse_id应该为null
                    'warehouse_name' => $parentGroup['parent_warehouse_info']['name'],
                    'quantity' => $parentGroup['total_quantity'],
                    'inventory_ids' => implode(',', $allInventoryIds),
                    'allow_zero_stock_sale' => $parentGroup['total_allow_zero_stock_sale'],
                    'real_arrival_date' => implode(',', array_unique($parentGroup['total_real_arrival_dates'])),
                    'price' => $processedParentPrices[214] ?? '',       // 美金价格
                    'price_rmb' => $processedParentPrices[4] ?? '',     // 人民币价格
                    'remark' => $processedParentRemarks[214] ?? '',     // 美金备注
                    'remark_rmb' => $processedParentRemarks[4] ?? '',   // 人民币备注
                    'first_leg_logistics_fee' => $processedParentPreWarehousePrices[214] ?? '',        // 美金前置仓价格
                    'first_leg_logistics_fee_rmb' => $processedParentPreWarehousePrices[4] ?? '',     // 人民币前置仓价格
                    'children' => []  // 全部为一级仓库时没有第三层
                ];
            } else {
                // 有二级仓库存在，显示完整的三层结构
                // 组装子仓库数据（第三层）
                $children = [];
                foreach ($parentGroup['child_warehouses'] as $childWarehouseId => $childData) {
                    // 获取子仓库的价格和备注信息（按货币分组）
                    $childPricesByCurrency = [];
                    $childRemarksByCurrency = [];
                    $childPreWarehousePricesByCurrency = [];
                    if (isset($priceData[$childWarehouseId])) {
                        foreach ($childData['inventory_ids'] as $inventoryId) {
                            if (isset($priceData[$childWarehouseId][$inventoryId])) {
                                foreach ($priceData[$childWarehouseId][$inventoryId] as $currencyId => $price) {
                                    $childPricesByCurrency[$currencyId][] = $price;
                                }
                            }
                        }
                    }
                    if (isset($remarkData[$childWarehouseId])) {
                        foreach ($childData['inventory_ids'] as $inventoryId) {
                            if (isset($remarkData[$childWarehouseId][$inventoryId])) {
                                foreach ($remarkData[$childWarehouseId][$inventoryId] as $currencyId => $remark) {
                                    if (!empty($remark)) {
                                        $childRemarksByCurrency[$currencyId][] = $remark;
                                    }
                                }
                            }
                        }
                    }
                    if (isset($preWarehousePriceData[$childWarehouseId])) {
                        foreach ($childData['inventory_ids'] as $inventoryId) {
                            if (isset($preWarehousePriceData[$childWarehouseId][$inventoryId])) {
                                foreach ($preWarehousePriceData[$childWarehouseId][$inventoryId] as $currencyId => $preWarehousePrice) {
                                    $childPreWarehousePricesByCurrency[$currencyId][] = $preWarehousePrice;
                                }
                            }
                        }
                    }
                    // 处理每种货币的价格和备注去重
                    $processedChildPrices = [];
                    foreach ($childPricesByCurrency as $currencyId => $prices) {
                        $processedChildPrices[$currencyId] = implode(',', array_unique($prices));
                    }

                    $processedChildRemarks = [];
                    foreach ($childRemarksByCurrency as $currencyId => $remarks) {
                        $processedChildRemarks[$currencyId] = implode(',', array_unique($remarks));
                    }

                    $processedChildPreWarehousePrices = [];
                    foreach ($childPreWarehousePricesByCurrency as $currencyId => $preWarehousePrices) {
                        $processedChildPreWarehousePrices[$currencyId] = implode(',', array_unique($preWarehousePrices));
                    }

                    $children[] = [
                        'productid' => $value['productid'],
                        'cname' => $value['cname'],
                        'arrival_date' => $value['arrival_date'],
                        'is_futures' => $value['is_futures'],
                        'fl_warehouse_id' => $childData['warehouse_info']['fl_warehouse_id'],
                        'warehouse_id' => $childWarehouseId,
                        'warehouse_name' => $childData['warehouse_info']['name'],
                        'quantity' => $childData['quantity'],
                        'inventory_ids' => implode(',', $childData['inventory_ids']),
                        'allow_zero_stock_sale' => $childData['allow_zero_stock_sale'],
                        'real_arrival_date' => implode(',', array_unique($childData['real_arrival_dates'])),
                        'price' => $processedChildPrices[214] ?? '',       // 美金价格
                        'price_rmb' => $processedChildPrices[4] ?? '',     // 人民币价格
                        'remark' => $processedChildRemarks[214] ?? '',     // 美金备注
                        'remark_rmb' => $processedChildRemarks[4] ?? '',   // 人民币备注
                        'first_leg_logistics_fee' => $processedChildPreWarehousePrices[214] ?? '',        // 美金前置仓价格
                        'first_leg_logistics_fee_rmb' => $processedChildPreWarehousePrices[4] ?? ''       // 人民币前置仓价格
                    ];
                }

                // 确保至少有一个子仓库（即使是空的）
                if (empty($children)) {
                    $children[] = [
                        'productid' => $value['productid'],
                        'cname' => $value['cname'],
                        'arrival_date' => $value['arrival_date'],
                        'is_futures' => $value['is_futures'],
                        'fl_warehouse_id' => $parentGroup['parent_warehouse_info']['fl_warehouse_id'],
                        'warehouse_id' => $parentId,
                        'warehouse_name' => $parentGroup['parent_warehouse_info']['name'],
                        'quantity' => $parentGroup['total_quantity'],
                        'inventory_ids' => '',
                        'allow_zero_stock_sale' => $parentGroup['total_allow_zero_stock_sale'],
                        'real_arrival_date' => implode(',', array_unique($parentGroup['total_real_arrival_dates'])),
                        'price' => $processedParentPrices[214] ?? '',       // 美金价格
                        'price_rmb' => $processedParentPrices[4] ?? '',     // 人民币价格
                        'remark' => $processedParentRemarks[214] ?? '',     // 美金备注
                        'remark_rmb' => $processedParentRemarks[4] ?? '',   // 人民币备注
                        'first_leg_logistics_fee' => $processedParentPreWarehousePrices[214] ?? '',        // 美金前置仓价格
                        'first_leg_logistics_fee_rmb' => $processedParentPreWarehousePrices[4] ?? ''       // 人民币前置仓价格
                    ];
                }

                // 组装父仓库数据（第二层）
                $value['children'][] = [
                    'productid' => $value['productid'],
                    'cname' => $value['cname'],
                    'arrival_date' => $value['arrival_date'],
                    'is_futures' => $value['is_futures'],
                    'fl_warehouse_id' => $parentId,
                    'warehouse_id' => null,  // 第二层的warehouse_id应该为null
                    'warehouse_name' => $parentGroup['parent_warehouse_info']['name'],
                    'quantity' => $parentGroup['total_quantity'],
                    'inventory_ids' => implode(',', $allInventoryIds),
                    'allow_zero_stock_sale' => $parentGroup['total_allow_zero_stock_sale'],
                    'real_arrival_date' => implode(',', array_unique($parentGroup['total_real_arrival_dates'])),
                    'price' => $processedParentPrices[214] ?? '',       // 美金价格
                    'price_rmb' => $processedParentPrices[4] ?? '',     // 人民币价格
                    'remark' => $processedParentRemarks[214] ?? '',     // 美金备注
                    'remark_rmb' => $processedParentRemarks[4] ?? '',   // 人民币备注
                    'first_leg_logistics_fee' => $processedParentPreWarehousePrices[214] ?? '',        // 美金前置仓价格
                    'first_leg_logistics_fee_rmb' => $processedParentPreWarehousePrices[4] ?? '',     // 人民币前置仓价格
                    'children' => $children  // 第三层：子仓库数据
                ];
            }
        }
    }


    /**
     * @describe 修改价格和折扣
     * @author: Bobo
     * @date: 2025-06-17 10:29:07 
     * @param [type] @required
     * @return Renderable
     */
    public function updatePriceAndDiscount($params)
    {
        $result = true;
        $this->model->startTrans();


        if (isset($params['is_futures']) && (isset($params['real_arrival_date']) && $params['real_arrival_date'])) { // 2025-07-14 批量修改期货的到货日期
            $updateModel = $this->model->name('inventory')
                ->where('is_futures', $params['is_futures'])
                ->where('productid', $params['productid'])
                ->where('arrival_date', $params['arrival_date'])
                ->where('is_del', 0);
            if (1 == $params['is_futures'] && $params['fl_warehouse_id'] && empty($params['wid'])) { // 批量修改在途期货，通过一级仓库
                $wid = $this->model->name('warehouse')->where('fl_warehouse_id', $params['fl_warehouse_id'])->where('is_del', 0)->column('id');
                $updateModel->where('wid', 'in', $wid);
            }

            if (!empty($params['wid'])) {
                $updateModel->where('wid', 'in', $params['wid']);
            }

            $updateResult = $updateModel->update(
                [
                    'real_arrival_date' => $params['real_arrival_date'],
                    'update_time' => date('Y-m-d H:i:s', time())
                ]
            );
        }

        if (1 == count($params['prices'])) { // 如果只有一个价格, 则添加一个价格为0
            array_unshift($params['prices'], [
                'value' => $params['prices'][0]['value'] == 214 ? 4 : 214,
                'price' => 0,
                'first_leg_logistics_fee' => 0,
                'remark' => '',
                'discount' => $params['prices'][0]['discount'],
            ]);
        }

        foreach ($params['prices'] as $key => $value) {
            $data = [
                'productid' => $params['productid'],
                'arrival_date' => $params['arrival_date'],
                'is_futures' => $params['is_futures'],
                'warehouse_id' => $params['wid'],
                'fl_warehouse_id' => $params['fl_warehouse_id'],
                'transaction_currency_id' => $value['value'],
                'price' => $value['price'],
                'first_leg_logistics_fee' => $value['first_leg_logistics_fee'],
                'remark' => $value['remark'],
                'discount' => $value['discount'],
                'creator' => $params['creator'],
            ];
            $updateResult = $this->update($data);
            if ($updateResult['code'] != 0) {
                $result = false;
                break;
            }

            $wid = [];
            if (!empty($params['wid'])) { // 如果指定了仓库ID，直接使用
                $wid = $params['wid'];
            } else { // 否则根据库存类型和前端仓库ID处理
                if ($params['is_futures'] == 0 || $params['is_futures'] == 1) {
                    if (!empty($params['fl_warehouse_id'])) {
                        $wid = $this->model->name('warehouse')
                            ->where('fl_warehouse_id', $params['fl_warehouse_id'])
                            ->where('is_del', 0)
                            ->column('id');

                        // 期货类型需要额外添加前端仓库ID
                        if ($params['is_futures'] == 1) {
                            $wid = array_merge($wid, [$params['fl_warehouse_id']]);
                        }
                    }
                }
                // 其他类型（is_futures == 2）保持空数组
            }

            $this->cannelPriceChangeAffectedRelatedOrders($params['productid'], $wid, $params['arrival_date'], $params['is_futures'], $value['value'], $value['price'], $value['first_leg_logistics_fee'], $value['discount']);
        }

        if ($result) {
            $this->model->commit();
        } else {
            $this->model->rollback();
        }
        return $result;
    }


    /**
     * @describe
     * @author: Bobo
     * @date: 2025-06-12 16:58:50 
     * @param [type] @required
     * @return Renderable
     */
    public function update($params)
    {
        $where[] = ['is_del', '=', 0];
        if (isset($params['productid'])) {
            $where[] = ['productid', '=', $params['productid']];
        }
        if (isset($params['arrival_date'])) {
            $where[] = ['arrival_date', '=', $params['arrival_date']];
        }
        if (isset($params['is_futures']) && $params['is_futures'] > -1) {
            $where[] = ['is_futures', '=', $params['is_futures']];
        }
        if (isset($params['fl_warehouse_id'])) {
            $wid = $this->model->name('warehouse')->where('fl_warehouse_id', $params['fl_warehouse_id'])->where('is_del', 0)->column('id');
            $wid = array_merge($wid, [$params['fl_warehouse_id']]);
            // 对于多个仓库ID，需要用多个 FIND_IN_SET 条件
            $whereOr = [];
            foreach ($wid as $singleWid) {
                $whereOr[] = ['wid', 'find in set', $singleWid];
            }
            if (!empty($whereOr)) {
                $where[] = function ($query) use ($whereOr) {
                    foreach ($whereOr as $index => $condition) {
                        if ($index === 0) {
                            $query->where($condition[0], $condition[1], $condition[2]);
                        } else {
                            $query->whereOr($condition[0], $condition[1], $condition[2]);
                        }
                    }
                };
            }
        } elseif (isset($params['warehouse_id'])) {
            $where[] = ['wid', '=', $params['warehouse_id']];
        }

        // 当fl_warehouse_id和warehouse_id同时存在且有值时，优先使用warehouse_id
        if (
            isset($params['fl_warehouse_id']) && isset($params['warehouse_id']) &&
            !empty($params['fl_warehouse_id']) && !empty($params['warehouse_id'])
        ) {
            // 移除之前添加的fl_warehouse_id条件，只使用warehouse_id
            $where = array_filter($where, function ($condition) {
                return !is_callable($condition);
            });
            if ($params['is_futures'] == 2) {
                $where[] = ['wid', 'find in set', $params['warehouse_id']];
            } else {
                $where[] = ['wid', '=', $params['warehouse_id']];
            }
        }

        // 获取库存数据（包含id和wid）
        $inventoryData = $this->model
            ->name('inventory')
            ->where(function ($query) {
                $query->whereRaw('(available_qty - lock_qty) > 0')
                    ->whereOr('allow_zero_stock_sale', 1);
            })
            ->where($where)
            ->field('id,wid')
            ->select()
            ->toArray();
        // 只有大期货需要展开多仓库记录
        if (2 == $params['is_futures']) {
            // 展开多仓库记录
            $expandedInventoryData = [];
            foreach ($inventoryData as $record) {
                $widArray = explode(',', $record['wid']);
                foreach ($widArray as $singleWid) {
                    $singleWid = trim($singleWid);
                    if (isset($params['warehouse_id']) && $params['warehouse_id'] > 0) {

                        if (!empty($singleWid) && $singleWid == $params['warehouse_id']) {
                            $expandedInventoryData[] = [
                                'id' => $record['id'],
                                'wid' => $singleWid
                            ];
                        }
                    } else {
                        if (!empty($singleWid)) {
                            $expandedInventoryData[] = [
                                'id' => $record['id'],
                                'wid' => $singleWid
                            ];
                        }
                    }
                }
            }
        } else {
            // 现货和在途期货直接使用原始数据，不需要展开
            $expandedInventoryData = $inventoryData;
        }
        // 提取所有的库存ID用于删除操作
        $inventoryIds = array_unique(array_column($expandedInventoryData, 'id'));

        $wid = array_unique(array_column($expandedInventoryData, 'wid'));

        // 开启事务
        $this->model->startTrans();
        try {
            $transactionCurrencyId = $params['transaction_currency_id'] ?? 214;
            // 删除旧的价格记录和对应的折扣数据
            if (!empty($inventoryIds)) {
                // 先获取要删除的价格记录ID
                $oldPriceIds = $this->model
                    ->name('product_price')
                    ->where('transaction_currency_id', $transactionCurrencyId)
                    ->where('inventory_id', 'in', $inventoryIds)
                    ->where('wid', 'in', $wid)
                    ->where('is_del', 0)
                    ->column('id');

                // 硬删除对应的折扣数据
                if (!empty($oldPriceIds)) {
                    $this->model->name('product_discount')->where('price_id', 'in', $oldPriceIds)->delete();
                }

                // 软删除价格记录
                $this->model->name('product_price')
                    ->where('transaction_currency_id', $transactionCurrencyId)
                    ->whereIn('inventory_id', $inventoryIds)
                    ->whereIn('wid', $wid)
                    ->update(['is_del' => time()]);
            }

            if (0 != $params['price']) { // 如果价格为0的话，默认删除原始价格，不新增价格 /** 2025-08-14 重要修改 */

                // 准备新的价格数据（使用展开后的数据）
                $productPriceList = [];
                $currentTime = date('Y-m-d H:i:s');

                foreach ($expandedInventoryData as $inventory) {
                    $productPriceList[] = [
                        'inventory_id' => $inventory['id'],
                        'wid' => $inventory['wid'],
                        'transaction_currency_id' => $transactionCurrencyId,
                        'price' => $params['price'],
                        'first_leg_logistics_fee' => $params['first_leg_logistics_fee'],
                        'remark' => $params['remark'],
                        'creator' => $params['creator'],
                        'create_time' => $currentTime
                    ];
                }

                $insertedPriceIds = [];
                // 批量插入价格数据
                if (!empty($productPriceList)) {
                    $this->model->name('product_price')->insertAll($productPriceList);

                    // 查询刚插入的价格记录ID
                    $insertedPriceIds = $this->model
                        ->name('product_price')
                        ->where('creator', $params['creator'])
                        ->where('create_time', $currentTime)
                        ->where('transaction_currency_id', $transactionCurrencyId)
                        ->where('price', $params['price'])
                        ->where('first_leg_logistics_fee', $params['first_leg_logistics_fee'])
                        ->where('is_del', 0)
                        ->where('inventory_id', 'in', array_column($expandedInventoryData, 'id'))
                        ->column('id');

                    // 批量插入折扣数据
                    if (!empty($insertedPriceIds)) {
                        $discountList = [];
                        foreach ($insertedPriceIds as $priceId) {
                            foreach ($params['discount'] as $discount) {
                                $discountList[] = [
                                    'level' => $discount['level'],
                                    'num' => $discount['num'],
                                    'price' => $discount['price'],
                                    'creator' => $params['creator'],
                                    'create_time' => $currentTime,
                                    'price_id' => $priceId
                                ];
                            }
                        }
                        if (!empty($discountList)) {
                            $this->model->name('product_discount')->insertAll($discountList);
                        }
                    }
                }
            }

            // 提交事务
            $this->model->commit();
            $this->clearCTerminalCache(6); // 清除C端产品缓存
            return $this->success([
                'inserted_price_ids' => $insertedPriceIds ?? [],
                'message' => '价格数据更新成功'
            ]);
        } catch (\Exception $e) {
            // 回滚事务
            $this->model->rollback();

            return $this->error(500001, '价格数据更新失败：' . $e->getMessage());
        }
    }


    /**
     *   获取 商品库存信息
     *   array $condition；
     *
     *   ===== 输入 =====
     * [
     * [
     * 'productid' => '商品ID',
     * 'wid' => '仓库',
     * 'arrival_date' => Null,
     * 'is_futures' => '0',
     * 'quantity' => '0'
     * ]
     * ];
     *
     *    ===== 输出  =====
     */

    public function getPrice(array $condition)
    {
        /* 判空 */
        if (empty($condition)) {
            return Basic::data(1, '库存参数不存在');
        }

        $Inventory = InventoryModel::field('id');
        foreach ($condition as $key => $value) {

            $where = [];

            if (!is_numeric($value['productid'])) {
                return Basic::data(1, 'KEY:' . $key . ' productid 参数错误');
            }

            if (!is_numeric($value['wid'])) {
                return Basic::data(1, 'KEY:' . $key . ' wid 参数错误');
            }

            if (!in_array($value['is_futures'], [0, 1, 2])) {
                return Basic::data(1, 'KEY:' . $key . ' is_futures 参数错误');
            }

            if (!is_numeric($value['quantity']) ||  $value['quantity'] <= 0) {
                return Basic::data(1, 'KEY:' . $key . ' quantity 参数错误');
            }


            $pay_quantity[implode('_', [
                $value['productid'],
                $value['wid'],
                $value['arrival_date'],
                $value['is_futures']
            ])] = $value['quantity'];


            /* 默认条件 */
            $where[] = ['is_del', '=', 0];
            $where[] = ['productid', '=', $value['productid']];
            $where[] = ['arrival_date', '=', is_null($value['arrival_date']) ? null : $value['arrival_date']];


            if ($key == 0) {
                $Inventory->field('id,wid,productid,arrival_date,is_futures')->where($where)->where(function ($query) {
                    $query->where(function ($query) {
                        $query->where('available_qty', '>', 0)->whereColumn('available_qty', '>', 'lock_qty');
                    })->whereOr('allow_zero_stock_sale', '=', 1);
                })
                    ->whereFindInSet('wid', $value['wid']);
            } else {
                $Inventory->union(function ($query) use ($value, $where) {
                    $query->table('db_inventory')->where($where)->where(function ($query) {
                        $query->where(function ($query) {
                            $query->where('available_qty', '>', 0)->whereColumn('available_qty', '>', 'lock_qty');
                        })->whereOr('allow_zero_stock_sale', '=', 1);
                    })->field('id,wid,productid,arrival_date,is_futures')->whereFindInSet('wid', $value['wid']);
                });
            }
        }

        $inventory = $Inventory->select();

        //        echo Db::getlastSql();
        //        die;

        if (!$inventory) {
            return Basic::data(1, '未找到库存信息');
        }

        $inventoryData = $inventory->toArray();

        /*  库存分组处理 */
        $groupedArray = [];
        $inventory_ids = [];
        foreach ($inventoryData as $item) {

            $key = implode('_', [
                $item['productid'],
                $item['wid'],
                $item['arrival_date'],
                $item['is_futures']
            ]);

            if (!isset($groupedArray[$key])) {
                $groupedArray[$key] = [
                    'productid' => $item['productid'],
                    'wid' => $item['wid'],
                    'arrival_date' => $item['arrival_date'],
                    'is_futures' => $item['is_futures'],
                    'inventory_id' => $item['id'],
                    'quantity' => $pay_quantity[$key],
                ];
                $inventory_ids[] = $item['id'];
            } else {
                continue;
            }

            unset($item['productid']);
            unset($item['wid']);
            unset($item['arrival_date']);
            unset($item['is_futures']);
        }

        //$data = array_values($groupedArray);

        /* 获取价格 */
        $product_price_where[] = ['transaction_currency_id', '=', '214'];
        $product_price_where[] = ['is_del', '=', '0'];
        $product_price_where[] = ['inventory_id', 'in', $inventory_ids];
        $RoductPrice = ProductPriceModel::with(['discount' => function ($query) {
            $query->field('num,rate,price,price_id')->order('level ESC');
        }])->where($product_price_where)->field('id,inventory_id,transaction_currency_id,price')
            ->select();

        if (!$RoductPrice) {
            return Basic::data(1, '未找到价格信息');
        }

        $RoductPrice = $RoductPrice->toArray();
        $RoductPriceColumn = [];
        foreach ($RoductPrice as $key => $value) {
            $key = $value['inventory_id'];
            $RoductPriceColumn[$key] = $value;
        }

        foreach ($groupedArray as $key => $value) {
            if (!isset($RoductPrice[$value['inventory_id']])) {
                $groupedArray[$key]['price'] = $RoductPriceColumn[$value['inventory_id']];
            } else {
                $groupedArray[$key]['price'] = [];
            }
        }

        $data = [];
        foreach ($groupedArray as $key => $item) {
            $data[$key]['productid'] = $item['productid'];
            $data[$key]['wid'] = $item['wid'];
            $data[$key]['arrival_date'] = $item['arrival_date'];
            $data[$key]['is_futures'] = $item['is_futures'];

            if (isset($item['price'])) {
                $data[$key]['price'] = $item['price']['price'];
                $data[$key]['sales_price'] = $this->getApplicablePrice($item['quantity'], $item['price']['discount']);
                $data[$key]['discount'] = $item['price']['discount'];
            } else {
                $data[$key]['price'] = null;
                $data[$key]['sales_price'] = null;
                $data[$key]['discount'] = [];
            }
        }

        return Basic::data(0, 'ok', $data);
    }


    /**
     * 获取适用的折扣价格
     * @param int   $quantity  购买数量
     * @param array $discounts 折扣规则数组
     * @return float 适用的折扣价格
     */
    function getApplicablePrice($quantity, $discounts)
    {
        // 按购买数量降序排列折扣规则
        usort($discounts, function ($a, $b) {
            return $b['num'] <=> $a['num'];
        });

        // 寻找第一个满足条件的折扣
        foreach ($discounts as $discount) {
            if ($quantity >= $discount['num']) {
                return $discount['price'];
            }
        }

        // 如果没有满足的则返回第一个折扣（最低阶梯）
        return $discounts[count($discounts) - 1]['price'];
    }

    /**
     * 取消价格变更影响到的相关订单
     * 
     * @param int $productId 商品ID
     * @param array $wid 仓库ID条件 （因为要兼容批量修改价格，所以这个参数直接传入数组）
     * @param string $realArrivalDate 真实到货日期
     * @param int $isFutures 库存类型
     * @param int $transaction_currency_id 交易币种ID
     * @param float $price 价格
     * @param float $firstLegLogisticsFee 头程物流费
     * @param array $discount 折扣信息
     * @return void
     */
    public function cannelPriceChangeAffectedRelatedOrders($productId, $wid, $realArrivalDate, $isFutures, $transaction_currency_id, $price, $firstLegLogisticsFee, $discount)
    {
        // 构建查询条件
        $where = [
            ['product_id', '=', $productId],
            ['real_arrival_date', '=', $realArrivalDate],
            ['is_futures', '=', $isFutures],
            ['o.is_del', '=', 0],
            ['quantity', '>', 0],
            ['transaction_currency_id', '=', $transaction_currency_id],
            ['o.status', 'in', [10, 21]],
            ['o.pay_status', '=', 1], // 支付状态为待支付
            ['o.order_type', '!=', 2], // 排除经销商发货订单
        ];
        if ($wid) { // 如果仓库ID不为空，则添加仓库ID条件 商品报价可能批量修改全部价格
            $where[] = ['warehouse_id', 'in', $wid];
        }

        // 查询受影响的订单
        $orderList = OrderItemModel::where($where)
            ->join('db_order o', 'o.id = db_order_item.order_id')
            ->join('db_customer c', 'c.id = o.user_id')
            ->field('db_order_item.*, o.id as order_id, o.status, o.is_del, o.owner, o.partner, o.order_category, o.pay_status, o.order_no,o.user_id,c.role')
            ->select();

        if (empty($orderList)) {
            return;
        }
        foreach ($orderList as $orderItem) {
            // 处理经销商订单的价格计算
            $currentPrice = $price;
            if ($orderItem->role === 'distributor') {
                $currentPrice = $discount[0]['price'] ?? $price; // 经销商订单默认使用最低阶梯价格
                foreach ($discount as $item) {
                    if ($orderItem->quantity >= $item['num']) {
                        $currentPrice = $item['price'];
                    }
                }
            }

            // 检查是否需要取消订单（价格或头程物流费发生变化）
            if ($currentPrice > $orderItem->actual_price || $firstLegLogisticsFee > $orderItem->first_leg_logistics_fee) {
                // 生成取消原因和信息
                $reason = '';
                $info = '';

                if ($currentPrice > $orderItem->actual_price && $firstLegLogisticsFee > $orderItem->first_leg_logistics_fee) {
                    $reason = '价格和头程物流费发生变化';
                    $info = sprintf(
                        '原价格：%s 原头程物流费：%s' . "\n\n" . '现价格：%s 现头程物流费：%s',
                        $orderItem->actual_price,
                        $orderItem->first_leg_logistics_fee,
                        $currentPrice,
                        $firstLegLogisticsFee
                    );
                } elseif ($currentPrice > $orderItem->actual_price) {
                    $reason = '价格发生变化';
                    $info = sprintf('原价格：%s 现价格：%s', $orderItem->actual_price, $currentPrice);
                } elseif ($firstLegLogisticsFee > $orderItem->first_leg_logistics_fee) {
                    $reason = '头程物流费发生变化';
                    $info = sprintf('原头程物流费：%s 现头程物流费：%s', $orderItem->first_leg_logistics_fee, $firstLegLogisticsFee);
                }

                // 发送系统通知
                try {
                    $completeNotificationService = new CompleteNotificationService();

                    $partner = $orderItem->partner ? explode(',', $orderItem->partner) : [];
                    $recipients = array_unique([$orderItem->owner, ...$partner]);
                    $orderType = $orderItem->order_category === 'wholesal' ? '存入资产' : '普通';
                    $content = sprintf(
                        "您负责的%s订单由于%s，已自动取消，请及时跟进\n\n%s\n\n",
                        $orderType,
                        $reason,
                        $info
                    );
                    $orderData = [
                        'id' => $orderItem->order_id,
                        'order_no' => $orderItem->order_no,
                        'order_category' => $orderItem->order_category,
                    ];
                    $res = $completeNotificationService->send('order_cancel', $orderData, $recipients, $content);
                    if ($res['code'] !== 0) {
                        Log::error('发送订单取消通知失败: ' . $res['message'] . ' 订单ID: ' . $orderItem->order_id);
                    }
                } catch (\Throwable $th) {
                    Log::error('发送订单取消通知失败: ' . $th->getMessage() . ' 订单ID: ' . $orderItem->order_id);
                }

                // 发送邮件通知
                try {
                    $mailService = new Mail();
                    $mailService->send('order_cancel_price_change', $orderItem->toArray());
                } catch (\Throwable $th) {
                    Log::error('发送订单取消邮件失败: ' . $th->getMessage() . ' 订单ID: ' . $orderItem->order_id);
                }

                // 更新订单状态
                try {
                    $this->model->name('order')->where('id', $orderItem->order_id)->update([
                        'status' => 70,
                        'update_time' => date('Y-m-d H:i:s')
                    ]);
                } catch (\Throwable $th) {
                    Log::error('取消价格变更影响到的订单失败: ' . $th->getMessage() . ' 订单ID: ' . $orderItem->order_id);
                }
            }
        }
    }
}
